<?php

namespace Lib;

class Html {

	public function select($aParam) {
		$aBefore = $aParam ['before'];
		$aAfter = $aParam ['after'];
		$aSelect = $aParam ['select'];
		if (is_string ( $aParam ['option'] ) && strpos ( $aParam ['option'], ':' )) {
			list ( $sMin, $sMax ) = explode ( ':', $aParam ['option'] );
			preg_match ( '/^([a-z]*)(\d+)$/', $sMin, $aMinmatch );
			preg_match ( '/^([a-z]*)(\d+)$/', $sMax, $aMaxmatch );
			if ($aMinmatch [1] == $aMaxmatch [1]) {
				$aOption = array ();
				for($i = $sMin; $i <= $sMax; $i ++) {
					$aOption [$i] = $i;
				}
			} else {
				$aOption = array ();
			}
		}
		
		if (is_array ( $aParam ['option'] )) {
			$sOption = $this->_getOption ( $aParam ['option'], $aParam ['default'] );
		}
		
		if (is_array ( $aBefore )) {
			$sBefore = $this->_getOption ( $aParam ['before'], $aParam ['default'] );
		}
		
		if (is_array ( $aAfter )) {
			$sAfter = $this->_getOption ( $aParam ['after'], $aParam ['default'] );
		}
		unset ( $aParam ['option'], $aParam ['default'] );
		$sHtml = '<select';
		foreach ( $aParam as $sKey => $sRow ) {
			$sHtml .= ' ' . $sKey . '="' . $sRow . '"';
		}
		$sHtml .= '>' . $sBefore . $sOption . $sAfter . '</select>';
		return $sHtml;
	}

	private function _getOption($aOption, $sDefault) {
		$sHtml = '';
		foreach ( $aOption as $sKey => $sRow ) {
			if (is_array ( $sRow ) && ! isset ( $sRow ['attr'] ) && ! isset ( $sRow ['text'] )) {
				$sHtml .= '<optgroup label="' . $sKey . '">';
				$sHtml .= $this->_getOption ( $sRow, $sDefault );
				$sHtml .= '</optgroup>';
			} else {
				if (is_array ( $sDefault )) {
					if (in_array ( $sKey, $sDefault )) {
						$sHtml .= '<option value="' . $sKey . '" selected';
					} else {
						$sHtml .= '<option value="' . $sKey . '"';
					}
				} elseif ($sDefault !== null && $sDefault == $sKey) {
					$sHtml .= '<option value="' . $sKey . '" selected';
				} else {
					$sHtml .= '<option value="' . $sKey . '"';
				}
				if (is_array ( $sRow )) {
					$sHtml .= ' ' . $sRow ['attr'] . '>' . $sRow ['text'] . '</option>';
				} else {
					$sHtml .= '>' . $sRow . '</option>';
				}
			}
		}
		return $sHtml;
	}
}

?>